{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def mult(chain):\n",
    "    n = len(chain)\n",
    "    \n",
    "    # single matrix chain has zero cost\n",
    "    aux = {(i, i): (0,) + chain[i] for i in range(n)}\n",
    "\n",
    "    # i: length of subchain\n",
    "    for i in range(1, n):\n",
    "        # j: starting index of subchain\n",
    "        for j in range(0, n - i):\n",
    "            best = float('inf')\n",
    "\n",
    "            # k: splitting point of subchain\n",
    "            for k in range(j, j + i):\n",
    "                # multiply subchains at splitting point\n",
    "                lcost, lname, lrow, lcol = aux[j, k]\n",
    "                rcost, rname, rrow, rcol = aux[k + 1, j + i]\n",
    "                cost = lcost + rcost + lrow * lcol * rcol\n",
    "                var = '(%s%s)' % (lname, rname)\n",
    "\n",
    "                # pick the best one\n",
    "                if cost < best:\n",
    "                    best = cost\n",
    "                    aux[j, j + i] = cost, var, lrow, rcol\n",
    "\n",
    "    return dict(zip(['cost', 'order', 'rows', 'cols'], aux[0, n - 1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'cols': 40, 'cost': 18000, 'order': '((AB)C)', 'rows': 10}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mult([('A', 10, 20), ('B', 20, 30), ('C', 30, 40)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'cols': 1, 'cost': 110, 'order': '(A(B(C(DE))))', 'rows': 10}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mult([('A', 10, 5), ('B', 5, 1), ('C', 1, 5), ('D', 5, 10), ('E', 10, 1)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
